package org.apache.commons.logging.impl;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

public class MetaTagsUtility {

	private static Element[] metas;
	
	/**
	 * Get all meta tag defined
	 * @return - List of meta tag 
	 */
	public static Element[] getAllMetas() {
        if(metas!=null){
        	return metas;
        }
        
		final JavaScriptObject metasHandel = getMetaTags();
        final int metasLen = getMetaTagsLength(metasHandel);
        metas = new Element[metasLen];
        for (int i=0; i < metasLen; i++) {
            metas[i] = getMetaTag(metasHandel, i);
        }
        return metas;
    }

	/**
	 * Get a meta with a specific name
	 * @param name - name of meta tag required
	 * @return Element[] - Subset of meta tag define with param name 
	 */
	public static Element[] getMetas(String name){
		if (metas == null) {
			getAllMetas();
		}
        
		List mymetas = new ArrayList();
		for (int i=0; i < metas.length; i++) {
            final Element c = metas[i];
            final String myName = DOM.getAttribute(c, "name");
            if (name.equals(myName)) {
            	mymetas.add( c);
            }
        }
		
		return (Element[]) mymetas.toArray(new Element[mymetas.size()]);
        		
	}
	
    private static native JavaScriptObject getMetaTags() /*-{
        return $doc.getElementsByTagName("meta");
    }-*/;

    private static native int getMetaTagsLength(JavaScriptObject metas) /*-{
        return metas.length;
    }-*/;

    private static native Element getMetaTag(JavaScriptObject metas, int i) /*-{
        return metas[i];
    }-*/;
}
